package com.qzdsoft.erpcloud.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.qzdsoft.JWTProperties;
import com.qzdsoft.erpcloud.service.sys.RedisService;
import com.qzdsoft.utils.StringUtil;
import com.qzdsoft.utils.SysUtils;
import com.qzdsoft.utils.constant.RedisConstant;

@Component
public class SessionExtendsInterceptor implements HandlerInterceptor 
{

    private Logger logger = LoggerFactory.getLogger(UserLoginInterceptor.class);
    
    @Autowired
    private JWTProperties jwtProperties;
    
    @Autowired
    private RedisService redisService;
    
    @Value("${login.validate}")
    private Boolean loginValidate;
    
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception
    {
        
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView handler) throws Exception
    {
        
        
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        
      //如果配置文件配置不需要登录验证 直接返回true （开发时可以配置为false）
        if(loginValidate==false) {
            return true;
        }
        Cookie cookies[] = request.getCookies();
        Integer uid = null;
        for(Cookie c:cookies) {
            logger.debug("获取到的token:{},value:{}",c.getName(),c.getValue());
            if("uid".equals(c.getName())) {
                uid = Integer.parseInt(c.getValue());
                break;
            }
        }
        if(StringUtil.isEmpty(uid)) {
            throw new RuntimeException("用户没有登录，不能访问");
        }
        
        Object userJson = redisService.get(SysUtils.redisUserSessionId(uid));
        if(userJson!=null) {
            redisService.set(SysUtils.redisUserSessionId(uid),redisService.get(SysUtils.redisUserSessionId(uid)).toString(),jwtProperties.getTokenExpriseTime());
            Object urlsObj = redisService.get(RedisConstant.reidsAuthorizedUrl+"_"+uid);
            if(urlsObj!=null) {
                redisService.set(RedisConstant.reidsAuthorizedUrl+"_"+uid,urlsObj.toString(),jwtProperties.getTokenExpriseTime());
            }
            Object buts = redisService.get(RedisConstant.redisButton+"_"+uid);
            if(buts!=null) {
                redisService.set(RedisConstant.redisButton+"_"+uid,buts.toString(),jwtProperties.getTokenExpriseTime());
            }
        }
        return true;
    }
}

